package cz.zcu.fav.rat.managed.validator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import org.joda.time.LocalDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import cz.zcu.fav.rat.managed.bean.calendar.AbstractCalendarBean;
import cz.zcu.fav.rat.managed.locale.LocaleMessageFactory;

@FacesValidator(value = "reservationValidator")
public class ReservationValidator implements Validator
{
	@Override
	public void validate(FacesContext arg0, UIComponent component, Object arg2)
			throws ValidatorException
	{
		DateTimeFormatter formatter = DateTimeFormat
				.forPattern(AbstractCalendarBean.DATE_VIEW_PATTERN);

		UIInput sinceInput = (UIInput) component.getAttributes().get("since");
		UIInput toInput = (UIInput) component.getAttributes().get("to");

		String sinceAsString = (String) sinceInput.getSubmittedValue();
		String toAsString  = "";
		 toAsString = (String) toInput.getSubmittedValue();
	

		LocalDateTime sinceJoda = formatter.parseDateTime(sinceAsString)
				.toLocalDateTime();
		LocalDateTime toJoda = formatter.parseDateTime(toAsString)
				.toLocalDateTime();

		validateDate(sinceInput, toInput, sinceJoda, toJoda);

	}


	protected void validateDate(UIInput sinceInput, UIInput toInput,
			LocalDateTime sinceJoda, LocalDateTime toJoda)
	{
//		if (sinceJoda.isBefore(LocalDateTime.now().minusMinutes(1)))
//		{
//			sinceInput.setValid(false);
//			throwDateInPast();
//		}
		if (toJoda.isBefore(LocalDateTime.now()))
		{
			toInput.setValid(false);
			throwDateInPast();
		}

		if (toJoda.isBefore(sinceJoda) || toJoda.isEqual(sinceJoda))
		{
			toInput.setValid(false);
			throwToGreater();
		}
	}

	private void throwToGreater() throws ValidatorException
	{
		String message = LocaleMessageFactory
				.getLocale("view.calendar.error.todategreater");

		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
				message, null);

		throw new ValidatorException(msg);

	}

	private void throwDateInPast() throws ValidatorException
	{
		String message = LocaleMessageFactory
				.getLocale("view.calendar.error.dateinpast");

		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
				message, null);

		throw new ValidatorException(msg);

	}

//	private ReservationService getReservationService()
//	{
//		if (reservationService == null)
//		{
//			reservationService = SpringBeanFactory.getInstance().getBean(
//					"reservationService", ReservationService.class);
//
//		}
//		return reservationService;
//	}

}
